import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { MapPin, Clock, Trophy, Star, Eye, RotateCcw } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface SpatialMemoryTestProps {
  onComplete: (result: TestResult) => void;
}

interface GridItem {
  id: number;
  row: number;
  col: number;
  isTarget: boolean;
  clicked: boolean;
}

interface Trial {
  id: number;
  targets: GridItem[];
  gridSize: number;
  level: number;
}

export function SpatialMemoryTest({ onComplete }: SpatialMemoryTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentTrial, setCurrentTrial] = useState(0);
  const [currentLevel, setCurrentLevel] = useState(1);
  const [trials, setTrials] = useState<Trial[]>([]);
  const [grid, setGrid] = useState<GridItem[]>([]);
  const [showingTargets, setShowingTargets] = useState(false);
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(420); // 7分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [correctSequences, setCorrectSequences] = useState(0);
  const [phaseStartTime, setPhaseStartTime] = useState<number>(0);
  const [memoryPhase, setMemoryPhase] = useState<'showing' | 'waiting' | 'recalling'>('showing');

  const MAX_LEVEL = 8;
  const TRIALS_PER_LEVEL = 3;
  const GRID_SIZE = 4; // 4x4网格

  const generateTrial = (level: number): Trial => {
    const targetCount = Math.min(level + 2, 8); // 3-8个目标
    const targets: GridItem[] = [];
    const usedPositions = new Set<string>();

    for (let i = 0; i < targetCount; i++) {
      let row: number, col: number;
      do {
        row = Math.floor(Math.random() * GRID_SIZE);
        col = Math.floor(Math.random() * GRID_SIZE);
      } while (usedPositions.has(`${row}-${col}`));
      
      usedPositions.add(`${row}-${col}`);
      targets.push({
        id: i,
        row,
        col,
        isTarget: true,
        clicked: false
      });
    }

    return {
      id: currentTrial,
      targets,
      gridSize: GRID_SIZE,
      level
    };
  };

  const initializeGrid = (trial: Trial): GridItem[] => {
    const newGrid: GridItem[] = [];
    for (let row = 0; row < GRID_SIZE; row++) {
      for (let col = 0; col < GRID_SIZE; col++) {
        const isTarget = trial.targets.some(t => t.row === row && t.col === col);
        newGrid.push({
          id: row * GRID_SIZE + col,
          row,
          col,
          isTarget,
          clicked: false
        });
      }
    }
    return newGrid;
  };

  useEffect(() => {
    if (stage === 'test') {
      const newTrials: Trial[] = [];
      for (let level = 1; level <= MAX_LEVEL; level++) {
        for (let trial = 0; trial < TRIALS_PER_LEVEL; trial++) {
          newTrials.push(generateTrial(level));
        }
      }
      setTrials(newTrials);
      
      if (newTrials.length > 0) {
        const firstTrial = newTrials[0];
        setGrid(initializeGrid(firstTrial));
        setCurrentLevel(firstTrial.level);
        startShowingPhase();
      }
    }
  }, [stage]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const startShowingPhase = () => {
    setMemoryPhase('showing');
    setShowingTargets(true);
    setPhaseStartTime(Date.now());
    
    // 显示时间根据难度调整：1.5-3秒
    const showTime = Math.min(3000, 1500 + currentLevel * 200);
    
    setTimeout(() => {
      setShowingTargets(false);
      setMemoryPhase('waiting');
      
      // 等待0.5秒后进入回忆阶段
      setTimeout(() => {
        setMemoryPhase('recalling');
      }, 500);
    }, showTime);
  };

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
  };

  const handleGridClick = (item: GridItem) => {
    if (memoryPhase !== 'recalling' || selectedItems.includes(item.id)) return;

    const newSelectedItems = [...selectedItems, item.id];
    setSelectedItems(newSelectedItems);

    const newGrid = grid.map(gridItem =>
      gridItem.id === item.id ? { ...gridItem, clicked: true } : gridItem
    );
    setGrid(newGrid);

    const trial = trials[currentTrial];
    const targetIds = trial.targets.map(t => t.row * GRID_SIZE + t.col);

    // 检查是否选择了所有目标
    if (newSelectedItems.length === trial.targets.length) {
      // 检查正确性
      const correct = targetIds.every(id => newSelectedItems.includes(id)) &&
                    newSelectedItems.every(id => targetIds.includes(id));
      
      if (correct) {
        setScore(prev => prev + currentLevel * 10);
        setCorrectSequences(prev => prev + 1);
      }
      
      // 延迟后进入下一试次
      setTimeout(() => {
        if (currentTrial < trials.length - 1) {
          const nextTrial = currentTrial + 1;
          setCurrentTrial(nextTrial);
          setCurrentLevel(trials[nextTrial].level);
          setGrid(initializeGrid(trials[nextTrial]));
          setSelectedItems([]);
          startShowingPhase();
        } else {
          setStage('results');
        }
      }, 1000);
    }
  };

  const handleComplete = () => {
    const totalTrials = trials.length;
    const accuracy = Math.round((correctSequences / totalTrials) * 100);
    const averageLevel = Math.round(correctSequences > 0 ? score / (correctSequences * 10) : 1);
    
    // 空间记忆跨度 (最高完成的连续级别)
    let memorySpan = 1;
    for (let level = 1; level <= MAX_LEVEL; level++) {
      const levelTrials = trials.filter(t => t.level === level);
      const levelCorrect = levelTrials.filter((_, index) => {
        const trialIndex = trials.findIndex(t => t.level === level) + levelTrials.indexOf(_);
        return trialIndex < correctSequences;
      }).length;
      
      if (levelCorrect >= 2) { // 至少对2/3
        memorySpan = level;
      } else {
        break;
      }
    }

    const finalScore = Math.min(100, Math.round(accuracy + (memorySpan - 1) * 5));
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'spatial-memory',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTrials,
        correctSequences,
        accuracy,
        spatialMemorySpan: memorySpan,
        averageLevel,
        maxLevel: Math.max(...trials.filter((_, i) => i < correctSequences).map(t => t.level)),
        totalScore: score
      }
    };

    onComplete(result);
  };

  const renderGrid = () => {
    return (
      <div className="grid grid-cols-4 gap-3 max-w-md mx-auto">
        {grid.map((item) => (
          <motion.button
            key={item.id}
            whileHover={{ scale: memoryPhase === 'recalling' ? 1.05 : 1 }}
            whileTap={{ scale: memoryPhase === 'recalling' ? 0.95 : 1 }}
            onClick={() => handleGridClick(item)}
            disabled={memoryPhase !== 'recalling'}
            className={`
              w-16 h-16 rounded-lg border-2 transition-all duration-200
              ${showingTargets && item.isTarget
                ? 'bg-blue-500 border-blue-600 shadow-lg'
                : item.clicked
                ? 'bg-green-400 border-green-500'
                : 'bg-slate-100 border-slate-300 hover:bg-slate-200'
              }
              ${memoryPhase === 'recalling' ? 'cursor-pointer' : 'cursor-not-allowed'}
            `}
          >
            {item.clicked && (
              <div className="text-white font-bold">
                {selectedItems.indexOf(item.id) + 1}
              </div>
            )}
          </motion.button>
        ))}
      </div>
    );
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-indigo-600 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <MapPin className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">空间记忆测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您对位置和空间关系的记忆能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-indigo-50 to-purple-50 rounded-xl p-6 border border-indigo-100">
              <h3 className="font-semibold text-indigo-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>观察4×4网格中亮起的方块位置</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>记住所有亮起方块的位置</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>在回忆阶段点击刚才亮起的所有位置</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-indigo-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>难度会逐渐增加，需要记忆更多位置</p>
                </div>
              </div>
            </div>

            {/* 测试流程图示 */}
            <div className="bg-slate-50 rounded-xl p-4 border border-slate-200">
              <h4 className="font-semibold text-slate-700 mb-3 text-center">测试流程</h4>
              <div className="flex items-center justify-center gap-4">
                <div className="flex flex-col items-center">
                  <Eye className="w-8 h-8 text-blue-500 mb-1" />
                  <span className="text-xs text-slate-600">观察</span>
                </div>
                <div className="text-slate-400">→</div>
                <div className="flex flex-col items-center">
                  <RotateCcw className="w-8 h-8 text-orange-500 mb-1" />
                  <span className="text-xs text-slate-600">等待</span>
                </div>
                <div className="text-slate-400">→</div>
                <div className="flex flex-col items-center">
                  <MapPin className="w-8 h-8 text-green-500 mb-1" />
                  <span className="text-xs text-slate-600">回忆</span>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">24</div>
                <div className="text-sm text-indigo-700">试次</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">8</div>
                <div className="text-sm text-purple-700">难度等级</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-purple-50 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">7</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-indigo-600 to-purple-500 hover:from-indigo-700 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const progress = (currentTrial / trials.length) * 100;
    const trial = trials[currentTrial];

    if (!trial) return null;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-indigo-100 text-indigo-700 border-indigo-300">
              试次 {currentTrial + 1} / {trials.length}
            </Badge>
            <Badge variant="outline" className="bg-purple-100 text-purple-700 border-purple-300">
              等级 {currentLevel}
            </Badge>
            <Badge variant="outline" className={`${
              memoryPhase === 'showing' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              memoryPhase === 'waiting' ? 'bg-orange-100 text-orange-700 border-orange-300' :
              'bg-green-100 text-green-700 border-green-300'
            }`}>
              {memoryPhase === 'showing' ? '观察阶段' :
               memoryPhase === 'waiting' ? '准备阶段' : '回忆阶段'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 指导信息 */}
        <Card className={`bg-gradient-to-r ${
          memoryPhase === 'showing' ? 'from-blue-50 to-blue-100 border-blue-200' :
          memoryPhase === 'waiting' ? 'from-orange-50 to-orange-100 border-orange-200' :
          'from-green-50 to-green-100 border-green-200'
        }`}>
          <CardContent className="py-4">
            <div className="text-center">
              <h3 className={`text-lg font-semibold ${
                memoryPhase === 'showing' ? 'text-blue-800' :
                memoryPhase === 'waiting' ? 'text-orange-800' :
                'text-green-800'
              }`}>
                {memoryPhase === 'showing' ? `记住亮起的 ${trial.targets.length} 个位置` :
                 memoryPhase === 'waiting' ? '准备回忆...' :
                 '点击刚才亮起的所有位置'}
              </h3>
              {memoryPhase === 'recalling' && (
                <p className="text-sm text-slate-600 mt-1">
                  已选择: {selectedItems.length} / {trial.targets.length}
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 测试网格 */}
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-lg">
          <CardContent className="py-12">
            <div className="text-center">
              {renderGrid()}
            </div>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalTrials = trials.length;
    const accuracy = Math.round((correctSequences / totalTrials) * 100);
    
    let memorySpan = 1;
    for (let level = 1; level <= MAX_LEVEL; level++) {
      const levelTrials = trials.filter(t => t.level === level);
      const levelCorrect = levelTrials.filter((_, index) => {
        const trialIndex = trials.findIndex(t => t.level === level) + levelTrials.indexOf(_);
        return trialIndex < correctSequences;
      }).length;
      
      if (levelCorrect >= 2) {
        memorySpan = level;
      } else {
        break;
      }
    }

    const finalScore = Math.min(100, Math.round(accuracy + (memorySpan - 1) * 5));

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-indigo-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-indigo-600 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-indigo-600 to-purple-500 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">空间记忆能力得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">{memorySpan}</div>
                <div className="text-sm text-indigo-700">记忆跨度</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">{accuracy}%</div>
                <div className="text-sm text-purple-700">准确率</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">正确序列</span>
                <span className="font-semibold text-slate-800">{correctSequences}/{totalTrials}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">最高等级</span>
                <span className="font-semibold text-slate-800">{Math.max(...trials.filter((_, i) => i < correctSequences).map(t => t.level))}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">总得分</span>
                <span className="font-semibold text-slate-800">{score}</span>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-indigo-600 to-purple-500 hover:from-indigo-700 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}